﻿using System;
using Microsoft.AspNetCore.Mvc;

namespace FlashPay.Admin.Controllers
{
    using FlashPay.Admin.ViewModels.User;
    using FlashPay.Entity;
    using FlashPay.Entity.Config;
    using FlashPay.Entity.Enum;
    using FlashPay.Entity.Response.User;
    using FlashPay.Service.Interface;
    using FlashPay.Util;
    using FlashPay.Util.GoogleAuthenticator;
    using Microsoft.AspNetCore.Http;
    using Microsoft.Extensions.Options;

    /// <summary>
    /// 账号控制器
    /// </summary>
    public class AccountController : Controller
    {
        #region 注入
        /// <summary>
        /// 缓存
        /// </summary>
        private readonly MemoryCacheUtil _memoryCacheUtil;

        /// <summary>
        /// 用户业务接口
        /// </summary>
        private readonly UserInfoService _userInfoService;

        /// <summary>
        /// 授权业务接口
        /// </summary>
        private readonly AuthorizeService _authorizeService;

        /// <summary>
        /// 权限业务接口
        /// </summary>
        private readonly PermissionService _permissionService;

        /// <summary>
        /// 
        /// </summary>
        private readonly AuthService _authService;

        /// <summary>
        /// 平台配置
        /// </summary>
        private readonly PlatformConfig _platformConfig;

        /// <summary>
        /// 票据
        /// </summary>
        public readonly IAuthenticate<TicketResponse> _manage;

        TwoFactorAuthenticator tfa;

        /// <summary>
        /// 注入
        /// </summary>
        /// <param name="sysRoleService"></param>
        /// <param name="userInfoService"></param>
        /// <param name="authorizeService"></param>
        public AccountController(MemoryCacheUtil memoryCacheUtil, UserInfoService userInfoService, AuthorizeService authorizeService,PermissionService permissionService, IAuthenticate<TicketResponse> manage, IOptions<PlatformConfig> option, AuthService authService, TwoFactorAuthenticator _tfa)
        {
            _memoryCacheUtil = memoryCacheUtil;
            _userInfoService = userInfoService;
            _authorizeService = authorizeService;
            _permissionService = permissionService;
            _manage = manage;
            _platformConfig = option.Value;
            _authService = authService;
            tfa = _tfa;
        }
        #endregion

        #region 登录
        public IActionResult Login()
        {
            return View();
        }

        //检测是否已登陆
        public JsonResult CheckLogin()
        {
            var response = new JResult<Object>()
            {
                Success = false
            };

            var token = string.IsNullOrEmpty(HttpContext.Request.Query["token"]) ? 
               HttpContext.Request.Headers["token"] :HttpContext.Request.Query["token"];

            if (string.IsNullOrEmpty(token))
            {
                response.ErrorMessage = "身份已过期,请重新登录";
                return Json(response);
            }
            var userData = _memoryCacheUtil.Get<TicketResponse>(EncryptHelper.deCryptDES(token));
            if (userData != null)
            {
                response.Data = userData;
                response.Success = true;
            }
            return Json(response);
        }

        /// <summary>
        /// 获取Token对象
        /// </summary>
        /// <param name="para">参数</param>
        [HttpPost]
        public JsonResult Login(AuthorizeViewModel para)
        {
            var response = new JResult<TokenResponse>()
            {
                Success = false
            };

            if (string.IsNullOrEmpty(para.Account))
            {
                response.ErrorMessage = "账号或密码错误！";
                return Json(response);
            }

            if (string.IsNullOrEmpty(para.Password))
            {
                response.ErrorMessage = "账号或密码错误！";
                return Json(response);
            }

            var loginRequest = new Entity.Request.User.LoginRequest()
            {
                Account = para.Account,
                Password = para.Password
            };

            var result = _userInfoService.Login(loginRequest);
            if (result.Success)
            {
                var tokenResponse = new TokenResponse() {
                    UserId = result.Data.UserId,
                    CompanyId = result.Data.CompanyId,
                    ULoggedIn = result.Data.ULoggedIn,
                    USecretKey = result.Data.USecretKey,
                    UShowQR = result.Data.UShowQR,
                    UserName = result.Data.UserName,
                    CompanyName = result.Data.CompanyName,
                };

                _manage.data = new TicketResponse() {
                    UserID = tokenResponse.UserId,
                    UserName = tokenResponse.UserName,
                    CompanyID = tokenResponse.CompanyId,
                    CompanyName = tokenResponse.CompanyName,
                    MType = 1,
                    Host = Request.Host.ToString(),
                    PlatformType = _platformConfig.Type,
                    UserPermission = result.Data.PermissionsCode,
                };

                //没有启用谷歌验证，并且secret值为空，直接登录成功
                if (result.Data.ULoggedIn != (int)UserInfoStatus.启用)
                {
                    var ticketStatus = _manage.SetTicket();
                    if (ticketStatus.Success)
                    {
                        tokenResponse.Token = ticketStatus.Data;
                    }
                    else
                    {
                        response.Success = false;
                        response.ErrorMessage = "登录失败";
                        return Json(response);
                    }
                }
                else
                {
                    _memoryCacheUtil.Set("UserInfo_" + tokenResponse.UserId, _manage.data, 10);
                }
                response.Data = tokenResponse;
                response.Success = true;
                response.SuccessMessage = "登录成功！";
            }
            else
            {
                response.Success = false;
                response.ErrorMessage = result.ErrorMessage;
            }
            return Json(response);
        }

        //检测验证码输入是否正确
        public JsonResult CheckCode([FromBody]TokenResponse login)
        {
            var response = new JResult<TokenResponse>()
            {
                Success = false
            };

            if (string.IsNullOrEmpty(login.Code))
            {
                response.ErrorMessage = "未获取到动态口令";
                return Json(response);
            }

            if (login.UserId == 0)
            {
                response.ErrorMessage = "未获取到用户ID";
                return Json(response);
            }

            string newKey = login.USecretKey;
            if (string.IsNullOrEmpty(newKey))
            {
                response.Success = false;
                response.ErrorMessage = "该账号未开启谷歌验证";
                return Json(response);
            }

            //var isCode = _memoryCacheUtil.Get<string>("UserCode_" + login.UserId);
            //if (isCode != null)
            //{
            //    response.Success = false;
            //    response.ErrorMessage = "操作频繁,请一分钟后再试";
            //    return Json(response);
            //}

            var result = tfa.ValidateTwoFactorPIN(newKey, login.Code);
            if (result)
            {
                TicketResponse tr = _memoryCacheUtil.Get<TicketResponse>("UserInfo_" + login.UserId);
                if (tr != null)
                {
                    _manage.data = tr;

                    var ticketStatus = _manage.SetTicket();
                    if (ticketStatus.Success)
                    {
                        response.Data = new TokenResponse
                        {
                            UserName = login.UserName,
                            CompanyName = tr.CompanyName,
                            Token = ticketStatus.Data
                        };
                    }
                }
                else
                {
                    response.ErrorMessage = "用户信息获取失败";
                    return Json(response);
                }
                if (login.UShowQR == (int)UserInfoLoggedIn.关闭)
                {
                    //设为已显示过二维码
                    UpdateUser(new EF.Models.UserInfo { UId = _manage.data.UserID, UShowQR = (int)Entity.Enum.UserInfoLoggedIn.开起 });
                }
                response.Success = true;
                response.SuccessMessage = "动态口令输入正确";
            }
            else
            {
                response.ErrorMessage = "动态口令输入错误";
            }

            return Json(response);
        }

        #endregion

        //获取二维码
        public JsonResult GetCode([FromBody]Entity.Request.User.LoginRequest login)
        {
            var response = new JResult()
            {
                Success = false
            };

            if (string.IsNullOrEmpty(login.Account) || string.IsNullOrEmpty(login.Password))
            {
                response.ErrorMessage = "获取二维码出错";
            }

            string code = tfa.GenerateSetupCode(null, login.Account + "@flashpay", login.Password, 260, 260).QrCodeSetupImageUrl;
            if (!string.IsNullOrEmpty(code))
            {
                response.Success = true;
                response.SuccessMessage = code;
            }
            return Json(response);
        }

        //修改用户信息
        public bool UpdateUser(EF.Models.UserInfo model)
        {
            EF.Models.UserInfo ui = new EF.Models.UserInfo();
            ui.UId = model.UId;
            ui.UShowQR = (int)Entity.Enum.UserInfoLoggedIn.开起;
            return _userInfoService.UpdateUserInfo(ui);
        }

    }
}